<?php

namespace SLN0002\DAO;

use Home\DAO\OrgDAO;
use Home\DAO\PSIBaseExDAO;

/**
 * 会计期间 DAO
 *
 * @author PSI
 * @copyright 2015 - present
 * @license GPL v3
 */
class GLPeriodDAO extends PSIBaseExDAO
{

  /**
   * 返回所有的公司列表
   */
  public function companyList($params)
  {
    $db = $this->db;

    $dao = new OrgDAO($db);
    $data = $dao->getCompanyExList($params);

    $result = [];

    foreach ($data as $v) {
      $id = $v["id"];

      // 查询当前会计期间
      $sql = "select acc_year, acc_month
              from t_acc_current_period
              where company_id = '%s' ";
      $d = $db->query($sql, $id);
      $currentPerido = "";
      if ($d) {
        $y = $d[0]["acc_year"];
        $m = $d[0]["acc_month"];
        if ($m < 10) {
          $m = "0{$m}";
        }
        $currentPerido = "{$y}-{$m}";
      }

      // 查询建账时间
      $sql = "select acc_year, acc_month, acc_gl_inited_dt, acc_detail_inited_dt
              from t_acc_init
              where company_id = '%s' ";
      $d = $db->query($sql, $id);
      $glInitDT = "";
      $detailInitDT = "";
      $initPeriod = "";
      if (!$d) {
        $glInitDT = "<span style='color:red'>未完成建账</span>";
        $detailInitDT = "<span style='color:red'>未完成建账</span>";
      } else {
        $y = $d[0]["acc_year"];
        $m = intval($d[0]["acc_month"]);
        if ($m < 10) {
          $m = "0{$m}";
        }
        $initPeriod = "{$y}-{$m}";
        $glInitDT = $d[0]["acc_gl_inited_dt"];
        if (!$glInitDT) {
          $glInitDT = "<span style='color:red'>未完成建账</span>";
        }
        $detailInitDT = $d[0]["acc_detail_inited_dt"];
        if (!$detailInitDT) {
          $detailInitDT = "<span style='color:red'>未完成建账</span>";
        }
      }

      $result[] = [
        "id" => $id,
        "code" => $v["code"],
        "name" => $v["name"],
        "orgType" => $v["orgType"],
        "currentPeriod" => $currentPerido,
        "initPeriod" => $initPeriod,
        "glInitDT" => $glInitDT,
        "detailInitDT" => $detailInitDT,
      ];
    }
    return $result;
  }

  /**
   * 某个公司的全部会计期间
   */
  public function periodList($params)
  {
    $db = $this->db;

    $companyId = $params["companyId"];

    // 查询建账期间
    $initYear = 0;
    $initMonth = 0;
    $sql = "select acc_year, acc_month
            from t_acc_init
            where company_id = '%s' ";
    $data = $db->query($sql, $companyId);
    if ($data) {
      $initYear = $data[0]["acc_year"];
      $initMonth = $data[0]["acc_month"];
    }

    // 查询当前期间
    $currentYear = 0;
    $currentMonth = 0;
    $sql = "select acc_year, acc_month
            from t_acc_current_period
            where company_id = '%s' ";
    $data = $db->query($sql, $companyId);
    if ($data) {
      $currentYear = $data[0]["acc_year"];
      $currentMonth = $data[0]["acc_month"];
    }

    $sql = "select acc_year, acc_month, acc_gl_closed,
              acc_detail_closed, period_closed
            from t_acc_period
            where company_id = '%s' 
            order by acc_year desc, acc_month desc";
    $data = $db->query($sql, $companyId);

    $result = [];
    $mark = "√";
    foreach ($data as $v) {
      $year = $v["acc_year"];
      $month = $v["acc_month"];

      $memo = "";
      if ($year == $initYear && $month == $initMonth) {
        $memo = "<span style='color:green'>建账期初期间</span>";
      } else if ($year == $currentYear && $month == $currentMonth) {
        $memo = "<span style='color:blue'>当前会计期间</span>";
      }

      $result[] = [
        "year" => $year,
        "month" => $month,
        "glClosed" => $v["acc_gl_closed"] == 1 ? $mark : null,
        "detailClosed" => $v["acc_detail_closed"] == 1 ? $mark : null,
        "periodClosed" => $v["period_closed"] == 1 ? $mark : null,
        "memo" => $memo,
      ];
    }

    return $result;
  }

  /**
   * 初始化某个公司的本年度会计期间
   */
  public function initPeriod(&$params)
  {
    $db = $this->db;

    $companyId = $params["companyId"];
    $year = intval($params["year"]);
    $month = intval($params["month"]);

    $sql = "select name from t_org where id = '%s' and parent_id is null ";
    $data = $db->query($sql, $companyId);
    if (!$data) {
      return $this->badParam("companyId");
    }
    $name = $data[0]["name"];

    $currentYear = intval(date("Y"));
    $yearIsOK = $year == $currentYear || $year == $currentYear - 1;
    if (!$yearIsOK) {
      return $this->bad("建账会计期间的年份只能是今年或去年");
    }

    if ($month < 0 || $month > 12) {
      return $this->bad("建账会计期间的年份不正确");
    }
    $currentMonth = intval(date("m"));
    if ($year == $currentYear) {
      if ($month > $currentMonth) {
        return $this->bad("建账会计期间不能超过当前服务器的月份");
      }
    }

    $sql = "select count(*) as cnt from t_acc_period
            where company_id = '%s'";
    $data = $db->query($sql, $companyId, $year);
    $cnt = $data[0]["cnt"];
    if ($cnt > 0) {
      return $this->bad("[{$name}]的会计期间已经初始化过了");
    }

    for ($m = $month; $m < 13; $m++) {
      $sql = "insert into t_acc_period(id, company_id, acc_year,acc_month,
              acc_gl_kept, acc_gl_closed, acc_detail_kept, acc_detail_closed,
              period_closed, year_forward)
            values ('%s', '%s', %d, %d,
              0, 0, 0, 0, 
              0, 0)";
      $rc = $db->execute($sql, $this->newId(), $companyId, $year, $m);
      if ($rc === false) {
        return $this->sqlError(__METHOD__, __LINE__);
      }
    }

    // 当前会计期间
    $sql = "delete from t_acc_current_period where company_id = '%s' ";
    $rc = $db->execute($sql, $companyId);
    if ($rc === false) {
      return $this->sqlError(__METHOD__, __LINE__);
    }

    $sql = "insert into t_acc_current_period(id, acc_year, acc_month, company_id)
            values ('%s', %d, %d, '%s')";
    $rc = $db->execute($sql, $companyId, $year, $month, $companyId);
    if ($rc === false) {
      return $this->sqlError(__METHOD__, __LINE__);
    }

    // 建账会计期间
    $sql = "delete from t_acc_init where company_id = '%s' ";
    $rc = $db->execute($sql, $companyId);
    if ($rc === false) {
      return $this->sqlError(__METHOD__, __LINE__);
    }
    $sql = "insert into t_acc_init(id, company_id, acc_year, acc_month, acc_gl_inited, acc_detail_inited)
            values ('%s', '%s', %d, %d, 0, 0)";
    $rc = $db->execute($sql, $this->newId(), $companyId, $year, $month);
    if ($rc === false) {
      return $this->sqlError(__METHOD__, __LINE__);
    }

    // 操作成功
    $params["log"] = "[{$name}] - 初始化会计期间";
    return null;
  }
}
